import urllib.request
import urllib.parse
import os
import time
import random

# 目标PDF文件名
pdf_filename = '人工智能对就业市场的影响数据集.pdf'
# 保存路径
save_dir = r'd:\D'
pdf_save_path = os.path.join(save_dir, pdf_filename)

# 基础URL模板（基于成功下载的URL格式）
base_url_template = "https://moor-smile.shec.edu.cn/rest/pdf/20250808/{uuid}/{filename}"

# 备用URL模板
alternative_url_templates = [
    "https://moor-smile.shec.edu.cn/api/pdf/20250808/{uuid}/{filename}",
    "https://moor-smile.shec.edu.cn/files/pdf/20250808/{uuid}/{filename}",
    "https://moor-smile.shec.edu.cn/pdf/20250808/{uuid}/{filename}"
]

# UUID组合（扩展更多可能性）
uuid_combinations = [
    # 之前使用过的UUID
    "84519de1-8bb4-4bd1-b3fa-e610b20d4408",  # 从成功下载的URL中提取的UUID
    "a1b2c3d4-e5f6-g7h8-i9j0-k1l2m3n4o5p6",
    "f9e8d7c6-b5a4-3d2c-1b0a-fedcba987654",
    "7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d",
    "4d3c2b1a-5f6e-7d8c-9b0a-1f2e3d4c5b6a",
    "a1234567-89bc-def0-1234-56789abcdef0",
    "11112222-3333-4444-5555-666677778888",
    "abcdef12-3456-7890-abcd-ef1234567890",
    
    # 新增更多UUID组合
    "00000000-0000-0000-0000-000000000001",
    "00000000-0000-0000-0000-000000000010",
    "00000000-0000-0000-0000-000000000100",
    "20250808-0000-0000-0000-000000000000",  # 包含日期的UUID
    "00000000-2025-0808-0000-000000000000",  # 包含日期的UUID变体
    "e4b89a4e-b810-4360-ba3c-8a2e9d8f7c6b",  # 随机生成的UUID
    "5f9e3b8d-1a7c-4d2b-9e6f-8c3a2d7f4b9a",  # 随机生成的UUID
    "9a8b7c6d-5e4f-3a2b-1c0d-9e8f7a6b5c4d"   # 随机生成的UUID
]

# 不同的HTTP请求头
user_agents = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59"
]

def download_pdf(url, headers):
    """尝试下载PDF文件"""
    try:
        print(f"尝试URL: {url}")
        req = urllib.request.Request(url, headers=headers)
        
        # 设置超时时间为10秒
        with urllib.request.urlopen(req, timeout=10) as response:
            # 检查响应状态码
            if response.status == 200:
                # 检查Content-Type是否为PDF
                content_type = response.getheader('Content-Type')
                if content_type and 'pdf' in content_type.lower():
                    # 读取并写入文件
                    data = response.read()
                    with open(pdf_save_path, 'wb') as out_file:
                        out_file.write(data)
                    
                    # 验证文件大小
                    if os.path.exists(pdf_save_path):
                        file_size = os.path.getsize(pdf_save_path)
                        if file_size > 100:  # 确保文件不为空
                            return True, file_size
                        else:
                            print(f"警告: 下载的文件可能是空的 (大小: {file_size} 字节)")
                            os.remove(pdf_save_path)
                            return False, 0
                else:
                    print(f"警告: 响应内容不是PDF文件 (Content-Type: {content_type})")
                    return False, 0
            else:
                print(f"HTTP错误: {response.status}")
                return False, 0
    except Exception as e:
        print(f"请求错误: {str(e)}")
        return False, 0

def main():
    print(f"开始尝试下载'{pdf_filename}'")
    print(f"保存路径: {pdf_save_path}")
    print(f"尝试UUID数量: {len(uuid_combinations)}")
    print(f"尝试URL模板数量: {1 + len(alternative_url_templates)}")
    
    start_time = time.time()
    total_attempts = 0
    success = False
    
    # 尝试所有UUID组合和URL模板
    for uuid in uuid_combinations:
        if success:
            break
            
        # 随机选择用户代理
        headers = {'User-Agent': random.choice(user_agents)}
        
        # 尝试所有URL模板
        all_templates = [base_url_template] + alternative_url_templates
        for template in all_templates:
            if success:
                break
                
            # 编码文件名
            encoded_filename = urllib.parse.quote(pdf_filename)
            # 构建完整URL
            url = template.format(uuid=uuid, filename=encoded_filename)
            
            # 下载PDF
            total_attempts += 1
            success, file_size = download_pdf(url, headers)
            
            # 如果成功，退出循环
            if success:
                print(f"\nPDF文件下载成功！")
                print(f"保存路径: {pdf_save_path}")
                print(f"文件大小: {file_size / 1024:.2f} KB")
                break
            
            # 随机延迟0.5-1.5秒，避免请求过于频繁
            time.sleep(random.uniform(0.5, 1.5))
    
    end_time = time.time()
    
    if not success:
        print(f"\n所有URL尝试都失败了。")
        print(f"总共尝试了 {total_attempts} 个URL组合")
        print(f"可能的原因:")
        print("1. 文件可能不存在或已被移动")
        print("2. 服务器可能限制了访问权限")
        print("3. 或者需要特定的请求头或认证信息")
        print("\n建议获取包含此PDF链接的HTML文件，或者确认文件是否存在于服务器上。")
    
    print(f"总耗时: {end_time - start_time:.2f} 秒")

if __name__ == "__main__":
    main()